<?php

namespace App\Http\Controllers\Api;


use App\Events\sendSubjectEcent;
use App\Events\WxLoginEvent;
use App\Http\Controllers\Controller;
use App\Models\Ask;
use App\Models\Mp;
use App\Models\Task;
use App\Models\TaskLog;
use Illuminate\Http\Request;
use App\Models\TposInfo;
use App\Models\User;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use App\Services\wxService;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class TposController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login', 'wxlogin', 'wxevent', 'getwxmsg']]);
    }

    public function login(Request $request)
    {
        if(!$request->has('mp') || empty($request->mp) || !is_numeric($request->mp) ){
            return $this->error('999', '服务端微信配置错误');
        }
        $wx_server = new wxService('miniapp',$request->mp);
        $server = $wx_server->run();
        $api = $server->getUtils();
        $req=$api->codeToSession($request->code);
    }

    public function wxlogin(Request $request)
    {
        if(!$request->has('mp') || empty($request->mp) || !is_numeric($request->mp) ){
            return $this->error('999', '服务端微信配置错误');
        }
        try {

            DB::beginTransaction();
            $wx_server = new wxService('miniapp',$request->mp);
            $app = $wx_server->run();
            $response = $app->getHttpClient()->request('GET', '/sns/jscode2session', [
                'query' => [
                    'appid' => $app->getAccount()->getAppId(),
                    'secret' => $app->getAccount()->getSecret(),
                    'js_code' => $request->code,
                    'grant_type' => 'authorization_code',
                ],
            ])->toArray(false);
            $storage=$wx_server->storageLogin($response);
            Log::info('微信登录回调：', $response);
            $user = User::where('wx_openid',$response['openid'])->first();

            if (empty($user)) {
                //不存在  创建用户
                $user=new User();
                $user->wx_openid = $response['openid'];
                $user->created_at = now()->toDateTimeString();
                $user->updated_at = now()->toDateTimeString();
                $user->password = bcrypt(123456);
                $user->mps_id=$request->mp;
                if($request->has('pid') && !empty($request->pid)){
                    $user->pid=$request->pid;
                }
                if($user->save()){
                    if($request->has('pid') && !empty($request->pid)){
                        $askarr=[
                            'user_id'=>$user->id,
                            'pid'=>$request->pid,
                            'amount'=>config("base.shareint"),
                        ];
                        $task = Task::find(5);
                        TaskLog::add($request->pid, $task->id, $task->price);
                        Ask::firstOrCreate($askarr,$askarr);
                    }
                    TposInfo::where('openid',$response['openid'])->update(['user_id'=>$user->id]);
                }
                DB::commit();
            } else {
                $user = $storage->user()->first();
            }
            $jwt_token = Auth::guard('api')->login($user);
            return $this->success('success',[
                'user' => $user,
                'token'      => 'Bearer ' . $jwt_token,
            ]);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error('333', $e->getMessage());
        }
    }

    public function wx_userinfo(Request $request)
    {
        $user = Auth::guard('api')->user();
        $tpos = TposInfo::findWhere('user_id', $user->id);
        $tpos->nickName && $user->nickname = $request->nickname;
        $tpos->avatarUrl && $user->avatar = $request->avatar;
        if($user->save() && $user->TposInfo()->save($tpos)){
            $task = Task::find(1);
            TaskLog::add($user->id, $task->id, $task->price);
            return $this->success('上传成功');
        }else{
            return $this->error('上传失败');
        }
    }

    public function wxevent()
    {
        $ss=event(new sendSubjectEcent(1,\App\Models\Video::TEMPLATE_ID['sendsub'],10));
        return $ss;
        $openid='oYlhD48I0vZNVYLhY8zSy-XEfwkQ';
        $m_id='rjQYmxFZJj7HJdehpzbQenfEtiba0xS1ArcMGdU1pcw';
        $data=['thing1'=>'猫和老鼠','time2'=>now()->toDateTimeString(),'thing3'=>'第100集','thing4'=>'好剧不断，速来观看'];
        $wxserver=new wxService('miniapp',1);
        $res=$wxserver->sendSubscribe($openid,$m_id,$data);
        return $res;
//        event(new WxLoginEvent(User::find(404)));
    }

    public function getwxmsg(Request $request, $mp = '')
    {
        Log::info($request->url(), [$request->all(), $mp]);
        if (empty($mp)) {
            return $this->error('错误');
        }
        $mp = $request->mp;
        $mchinfo = Mp::where('id', $mp)->where('status', 1)->first();
        $wx = new wxService('minimsg', $mchinfo->id);
        $app = $wx->run();
        $server = $app->getServer();
        $message = $server->getDecryptedMessage();
        Log::info('minimsg', ['type' => $message->MsgType, 'msg' => $message->Content, 'FromUserName' => $message->FromUserName]);
        $server->addMessageListener('text', function ($message, \Closure $next) use ($mchinfo) {
            if ($message->MsgType == 'text') {
                if ($message->Content == config("publicNotice.minimsg")) {
                    Log::info('minimsg', ['任务接入']);
                    $task = Task::find(4);
                    TaskLog::add(User::where('wx_openid', $message->FromUserName)->where('mps_id', $mchinfo->id)->value('id'), $task->id, $task->price);
                    return '任务完成';
                } else {
                    return '感谢关注';
                }
            } else {
                return '感谢关注';
            }
        });
        return $server->serve();
    }

    public function getMiniPhone(Request $request)
    {
        try {
            $user = Auth::guard('api')->user();
            if (empty($user)) {
                return $this->error('未登录');
            }
            $mp = $user->mps()->first();
            $wx = new wxService('miniapp', $mp->id);
            $app = $wx->run();
            $util = $app->getUtils();
            $sess = $util->codeToSession($request->code);
            $session_key = $sess['session_key'];
            $data = $util->decryptSession($session_key, $request->iv, $request->encryptedData);
            Log::info('微信手机号', [$data]);
            if (isset($data['phoneNumber'])) {
                $user->phone = $data['phoneNumber'];
                if ($user->save()) {
                    $task = Task::find(2);
                    TaskLog::add($user->id, $task->id, $task->price);
                    return $this->success('绑定成功');
                } else {
                    return $this->error('绑定失败');
                }
            } else {
                return $this->error('绑定失败1');
            }
        } catch (\Exception $exception) {
            return $this->error('绑定失败');
        }
    }
}
